<script setup lang="ts">
import { FwbInput, FwbButton } from 'flowbite-vue';

const { showToast } = useToast();
const { signin, signup } = useSign();

const loginMode = ref(true);

// 表单数据
const formData = reactive<Record<string, { value: string, status?: 'success' | 'error', msg: string }>>({
    signInName: { value: '', status: void 0, msg: '' },
    signInPassword: { value: '', status: void 0, msg: '' },
    signUpName: { value: '', status: void 0, msg: '' },
    signUpPassword: { value: '', status: void 0, msg: '' },
    signUpConfirm: { value: '', status: void 0, msg: '' },
});

const clearFormData = () => {
    // 清空表单数据
    Object.keys(formData).forEach(key => {
        formData[key].value = '';
        formData[key].status = void 0;
    });
};

watch(loginMode, () => {
    clearFormData();
});

const loading = ref(false);


const onChange = (e: FocusEvent) => {
    const input = e.target as HTMLInputElement;
    const name = input.name;
    const value = input.value;
    if (name.endsWith('Name')) {
        if (/\w{4,16}/.test(value)) {
            formData[name].status = 'success';
            formData[name].msg = '';
        } else {
            formData[name].status = 'error';
            formData[name].msg = 'Name should be no less than 4 characters and no more than 16 characters.';
        }
    }
    if (name.endsWith('Password')) {
        if (/\w{6,16}/.test(value)) {
            formData[name].status = 'success';
            formData[name].msg = '';
        } else {
            formData[name].status = 'error';
            formData[name].msg = 'Password should be no less than 4 characters and no more than 16 characters.';
        }
    }
    if (name.endsWith('Confirm')) {
        if (formData.signUpPassword.value === formData.signUpConfirm.value) {
            formData[name].status = 'success';
            formData[name].msg = '';
        } else {
            formData[name].status = 'error';
            formData[name].msg = 'The two passwords typed do not match.';
        }
    }
};

const onFormSubmit = async () => {
    let request;
    // 配置请求参数
    if (loginMode.value && formData.signInName.status === 'success' && formData.signInPassword.status === 'success') {
        request = signin({
            name: formData.signInName.value,
            password: formData.signInPassword.value,
        });
    } else if (!loginMode.value && formData.signUpName.status === 'success' && formData.signUpPassword.status === 'success' && formData.signUpConfirm.status === 'success') {
        request = signup({
            name: formData.signUpName.value,
            password: formData.signUpPassword.value,
        });
    } else return;
    // 提交表单
    try {
        loading.value = true;
        const { code, msg } = await request;
        showToast({ msg, type: code === 0 ? 'success' : 'danger' });
        // 相应跳转
        if (code === 0) {
            if (loginMode.value) {
                navigateTo('/home');
            } else {
                loginMode.value = true;
                // 自动填入
                const name = formData.signUpName.value;
                nextTick(() => {
                    formData.signInName.value = name;
                    formData.signInName.status = 'success';
                });
            }
        }
    }
    finally {
        loading.value = false;
    }
};
</script>

<template>
    <div class="w-full h-full relative" :class="loginMode ? 'signin' : 'signup'">
        <form @submit.prevent="onFormSubmit" class="w-3/5 h-full absolute transition-all duration-1000">
            <Transition name="fade" mode="out-in">
                <div v-if="loginMode" class="w-full h-full overflow-hidden flex flex-col justify-center items-center">
                    <h2 class="text-3xl leading-loose font-bold">Sign In Your Account</h2>
                    <div class="my-2 w-full flex justify-center gap-2">
                        <svg class="icon" :style="{ width: '1.5rem', height: '1.5rem' }" aria-hidden="true">
                            <use xlink:href="#icon-qq" />
                        </svg>
                        <svg class="icon" :style="{ width: '1.5rem', height: '1.5rem' }" aria-hidden="true">
                            <use xlink:href="#icon-weixinmw" />
                        </svg>
                    </div>
                    <fwb-input class="w-3/5" name="signInName" type="text" v-model="formData.signInName.value"
                        placeholder="enter your account name" label="Account Name" required
                        :validation-status="formData.signInName.status" @change="onChange">
                        <template #validationMessage>{{ formData.signInName.msg }}</template>
                    </fwb-input>
                    <fwb-input class="w-3/5" name="signInPassword" type="password"
                        v-model="formData.signInPassword.value" placeholder="enter your account password"
                        label="Account Password" :validation-status="formData.signInPassword.status" required
                        @change="onChange">
                        <template #validationMessage>{{ formData.signInPassword.msg }}</template>
                    </fwb-input>
                    <fwb-button type="submit" :loading="loading"
                        class="mt-8 w-40 h-12 rounded-full tracking-widest bg-element text-white font-bold">
                        SIGN IN
                    </fwb-button>
                </div>
                <div v-else class="w-full h-full overflow-hidden flex flex-col justify-center items-center">
                    <h2 class="text-3xl leading-loose font-bold">Create An Account</h2>
                    <fwb-input class="w-3/5" name="signUpName" type="text" v-model="formData.signUpName.value"
                        placeholder="enter your account name" label="Account Name"
                        :validation-status="formData.signUpName.status" required @change="onChange">
                        <template #validationMessage>{{ formData.signUpName.msg }}</template>
                    </fwb-input>
                    <fwb-input class="w-3/5" name="signUpPassword" type="password"
                        v-model="formData.signUpPassword.value" placeholder="enter your account password"
                        label="Account Password" :validation-status="formData.signUpPassword.status" required
                        @change="onChange">
                        <template #validationMessage>{{ formData.signUpPassword.msg }}</template>
                    </fwb-input>
                    <fwb-input class="w-3/5" name="signUpConfirm" type="password" v-model="formData.signUpConfirm.value"
                        placeholder="confirm your account password" label="Confirm Account Password"
                        :validation-status="formData.signUpConfirm.status" required @change="onChange">
                        <template #validationMessage>{{ formData.signUpConfirm.msg }}</template>
                    </fwb-input>
                    <fwb-button type="submit" :loading="loading"
                        class="mt-8 w-40 h-12 rounded-full tracking-widest bg-element text-white font-bold">
                        SIGN UP
                    </fwb-button>
                </div>
            </Transition>
        </form>
        <div class="w-2/5 h-full absolute transition-all duration-1000 shadow-xl
         before:content-[''] before:absolute before:w-full before:aspect-square before:rounded-full before:shadow-normal-inner
         before:transition-all before:duration-1000 before:translate-x-to-center before:translate-y-to-center
         after:content-[''] after:absolute after:w-2/5 after:aspect-square after:rounded-full after:shadow-normal-inner
         after:transition-all after:duration-1000 after:translate-x-to-center after:translate-y-to-center">
            <Transition name="fade" mode="out-in">
                <div v-if="loginMode" class="w-full h-full overflow-hidden flex flex-col justify-center items-center">
                    <h2 class="text-3xl leading-loose font-bold">Welcome Back To Chat!</h2>
                    <p class="leading-loose">New to chat? Create an account!</p>
                    <button class="mt-8 w-40 h-12 rounded-full tracking-widest bg-element text-white font-bold"
                        @click="loginMode = !loginMode">SIGN UP</button>
                </div>
                <div v-else class="w-full h-full overflow-hidden flex flex-col justify-center items-center">
                    <h2 class="text-3xl leading-loose font-bold">Hello New Friend!</h2>
                    <p class="leading-loose">Already have an account? Come and sign in</p>
                    <button class="mt-8 w-40 h-12 rounded-full tracking-widest bg-element text-white font-bold"
                        @click="loginMode = !loginMode">SIGN IN</button>
                </div>
            </Transition>
        </div>
    </div>
</template>

<style lang="scss">
.signin {
    &>form {
        left: 40%;
    }

    &>div {
        left: 0;

        &::before {
            left: 80%;
            bottom: -90%;
        }

        &::after {
            left: 20%;
            top: 0;
        }
    }
}

.signup {
    &>form {
        left: 0;
    }

    &>div {
        left: 60%;

        &::before {
            left: -10%;
            bottom: -90%;
        }

        &::after {
            left: 80%;
            top: 0;
        }
    }
}

.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}
</style>